package com.wondertek.service.service.business.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.util.security.LoginUser;
import com.wondertek.common.util.security.SecurityUtil;
import com.wondertek.service.dto.business.req.SiteAddReq;
import com.wondertek.service.dto.business.req.SitePageReq;
import com.wondertek.service.dto.business.req.SiteUpdateReq;
import com.wondertek.service.dto.business.res.SiteDetailRes;
import com.wondertek.service.entity.business.DevicePo;
import com.wondertek.service.entity.business.SitePo;
import com.wondertek.service.entity.business.UserSitePo;
import com.wondertek.service.mapper.business.SiteMapper;
import com.wondertek.service.service.business.DeviceService;
import com.wondertek.service.service.business.SiteService;
import com.wondertek.service.service.business.UserSiteService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description:
 * @author: qinjianhui
 * @create: 2024-07-16 14:10
 **/
@Service
public class SiteServiceImpl extends ServiceImpl<SiteMapper, SitePo> implements SiteService {
    @Resource
    private SiteMapper siteMapper;

    @Resource
    private UserSiteService userSiteService;

    @Resource
    private DeviceService deviceService;

    /*
    * 站点详情
    * */
    @Override
    public SiteDetailRes detail(String id) {
        return siteMapper.detail(id);
    }

    /*
    * 新增站点
    * */
    @Override
    public void addSite(SiteAddReq siteAddReq){
        //站点名称不能重复
        LambdaQueryWrapper<SitePo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SitePo::getIsDelete,0);
        lambdaQueryWrapper.eq(SitePo::getSiteName,siteAddReq.getSiteName());
        List<SitePo> list = this.list(lambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            throw new AppException("site.name.exist");
        }
        SitePo sitePo = new SitePo();
        BeanUtil.copyProperties(siteAddReq, sitePo);
        sitePo.setIsDelete(0);
        this.save(sitePo);
        //添加站点用户关系
        if(CollectionUtils.isNotEmpty(siteAddReq.getUserIds())){
            for(String userId : siteAddReq.getUserIds()){
                UserSitePo userSitePo = new UserSitePo();
                userSitePo.setSiteId(sitePo.getId());
                userSitePo.setUserId(userId);
                userSiteService.save(userSitePo);
            }
        }

    }

    /*
     * 删除站点
     * */
    @Override
    public void deleteSite(String id) {
        //先检查站点下的设备
        LambdaQueryWrapper<DevicePo> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DevicePo::getIsDelete,0);
        wrapper1.eq(DevicePo::getSiteId,id);
        List<DevicePo> list = deviceService.list(wrapper1);
        if (CollectionUtils.isNotEmpty(list)){
            throw new AppException("site.exists.device");
        }
        this.removeById(id);
        //删除用户站点关系
        LambdaQueryWrapper<UserSitePo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserSitePo::getSiteId,id);
        userSiteService.remove(wrapper);
    }

    /*
    * 查询站点
    * */
    @Override
    public Page<SitePo> page(SitePageReq sitePageReq) {
        //获取登陆人信息
        LoginUser loginUser = SecurityUtil.getLoginUser();
        String id = loginUser.getUserId();
        String userName = loginUser.getName();
        LambdaQueryWrapper<UserSitePo> userSitePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userSitePoLambdaQueryWrapper.eq(UserSitePo::getUserId,id);
        List<UserSitePo> list = userSiteService.list(userSitePoLambdaQueryWrapper);
        List<String> siteIds = list.stream().map(UserSitePo::getSiteId).collect(Collectors.toList());
        LambdaQueryWrapper<SitePo> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(sitePageReq.getSearchText())){
//            wrapper.or(i -> i.like(SitePo::getSiteName, sitePageReq.getSearchText()))
//                    .or(i -> i.like(SitePo::getAddress, sitePageReq.getSearchText()));
            wrapper.apply("(site_name like concat('%','"+sitePageReq.getSearchText()+"','%') or address like concat('%','"+sitePageReq.getSearchText()+"','%'))");
        }
        wrapper.eq(SitePo::getIsDelete, 0);
        if(CollectionUtils.isEmpty(siteIds)){
            siteIds.add("''");
        }
        if(!"admin".equals(userName)){
            wrapper.in(SitePo::getId,siteIds);
        }
        wrapper.orderByDesc(SitePo::getCreateTime);
        return this.page(new Page<>(sitePageReq.getPageNo(), sitePageReq.getPageSize()), wrapper);
    }

    /*
     * 修改站点
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSite(SiteUpdateReq siteUpdateReq) {
        //先查询原站点信息
        SitePo byId = this.getById(siteUpdateReq.getId());
        if(!siteUpdateReq.getSiteName().equals(byId.getSiteName())){
            //站点名称改变时校验名称是否重复
            LambdaQueryWrapper<SitePo> sitePoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sitePoLambdaQueryWrapper.eq(SitePo::getIsDelete,0);
            sitePoLambdaQueryWrapper.eq(SitePo::getSiteName,siteUpdateReq.getSiteName());
            List<SitePo> list = this.list(sitePoLambdaQueryWrapper);
            if(CollectionUtils.isNotEmpty(list)){
                throw new AppException("site.exists.device");
            }
        }
        SitePo sitePo = new SitePo();
        BeanUtil.copyProperties(siteUpdateReq, sitePo);
        this.updateById(sitePo);
        if(CollectionUtils.isNotEmpty(siteUpdateReq.getUserIds())){
            //先删除原站点用户关系，再建立新的
            LambdaQueryWrapper<UserSitePo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserSitePo::getSiteId,siteUpdateReq.getId());
            userSiteService.remove(wrapper);
            for(String userId : siteUpdateReq.getUserIds()){
                UserSitePo userSitePo = new UserSitePo();
                userSitePo.setUserId(userId);
                userSitePo.setSiteId(siteUpdateReq.getId());
                userSiteService.save(userSitePo);
            }
        }
    }

    /*
    * 通过userid查找站点
    * */
    @Override
    public List<SitePo> selectSiteByUserId(String userId) {
        return siteMapper.selectSiteByUserId(userId);
    }
}

